export const BASE_URL = "https://a.shiqin.wang/"


function getToken() {
	try {
		var user = uni.getStorageSync("shiqin-user")
		const token = user.token;
		if (token) {
			return token
		} else {
			return ''
		}
	} catch (e) {
		console.log(e)
	}
}

function getHeaders() {
	let token = getToken()
	let header = {
		'token': token,
		'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
	};
	return header
}


export default {
	get(url, param) {
		var user = uni.getStorageSync("shiqin-user")
		if (user.PQD) {
			if(param.PQD){
				param['PQD'] = param.PQD
			}else{
				param['PQD'] = user.PQD
			}
			param['token'] = user.token
			param['version'] = "6.4.8"
		}
		return new Promise((resolve, reject) => {
			uni.request({
				method: 'GET',
				url: BASE_URL + url,
				data: param,
				header: getHeaders()
			}).then(res => {
				switch (res[1].data.code) {
					case 1:
						resolve(res[1].data.data)
						break
					case 0:
						uni.showToast({
							title: res[1].data.msg,
							icon: 'none',
							duration: 1500
						});
						break
					case 401:
						uni.setStorageSync("shiqin-user", "")
						uni.showModal({
							title: "提示",
							content: "登录失效，请重新登录",
							success(res) {
								if (res.confirm) {
									uni.navigateTo({
										url: "/pages/index/index"
									})
								} else {
									reject({})
								}
							}
						});
						break
					default:
						reject(res)
						break
				}
			}).catch(
				(response) => {
					reject(response)
				}
			)
		})
	},
	post(url, param) {
		var user = uni.getStorageSync("shiqin-user")
		if (user && user.PQD) {
			if(param.PQD){
				param['PQD'] = param.PQD
			}else{
				param['PQD'] = user.PQD
			}
			param['token'] = user.token
			param['version'] = "6.4.8"
		}
		return new Promise((resolve, reject) => {
			uni.request({
				method: 'POST',
				url: BASE_URL + url,
				data: param,
				header: getHeaders()
			}).then(res => {
				uni.hideLoading()
				switch (res[1].data.code) {
					case 1:
						resolve(res[1].data.data)
						break
					case 0:
						if (url == 'api/apiv2/ActiveJoinTree') {
							//加入家谱出错，清除保存的数据
							var iniviteData = {
								treeId: '',
								treeName: '',
								inviteId: '',
								userPQD: "",
							}
							uni.setStorageSync("shiqin-user-invite", iniviteData)
						} else {
							uni.showToast({
								title: res[1].data.msg,
								icon: 'none',
								duration: 1500
							});
						}
						break
					case 401:
						uni.setStorageSync("shiqin-user", "")
						uni.showModal({
							title: "提示",
							content: "登录失效，请重新登录",
							success(res) {
								if (res.confirm) {
									uni.navigateTo({
										url: "/pages/index/index"
									})
								} else {
									reject({})
								}
							}
						});
						break
					default:
						reject(res)
						break
				}
			}).catch((response) => {
				reject(response)
			})
		})
	}
}
